package com.wsoft.utils;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.util.Base64;

/**
 * @Author Zhang gukai
 * @Date 2024/11/11 13:49
 */

@Component
public class Sm4EncryptionUtil {

    @Value("${encryption.key}")
    private String encryptionKey;

    private static final String ALGORITHM = "SM4";

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    public  String encrypt(String data) throws Exception {
        byte[] keyBytes = Hex.decode(encryptionKey);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    /**
     * 解密数据
     *
     * @param encryptedData 加密后的数据（Base64 编码）
     * @return 解密后的数据
     */
    public  String decrypt(String encryptedData) throws Exception {
        byte[] keyBytes = Hex.decode(encryptionKey);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedData);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }
}

